import React, { useState } from 'react';
import { observer, inject } from 'mobx-react';
import classNames from 'classnames';
import { Button, Space, Tag, Badge, List, Row, Col, Card, Tabs, Input, message, Spin } from 'antd';
import { ErrorData } from '@/pages/front/document/documentType';
import * as Util from '@/utils/util';
import { StoreProps } from '../store';
import styles from '../style/proofread.module.less';
import bannerImg from '@/assets/banner.png';

const prefix = 'proofread';

/**
 * 校对类型
 */
const proofTypes = [
  { label: '校对类型', value: 'all' },
  { label: '文档类型', value: 'politics' },
  { label: '自定义词', value: 'custom' },
];

/**
 * 文档类型
 */
const docTypes = [
  { label: '文档类型: 通用', value: 'common' },
  { label: '自定义词', value: 'custom' },
];

/**
 * 错误统计
 */
const errorStats = [
  { label: '全部错误', key: 'all', color: '#2973de' },
  { label: '严重错误', key: 'serious', color: '#f50' },
  { label: '疑似错误', key: 'suspect', color: '#e3b82f' },
  { label: '常见错误', key: 'normal', color: '#87d068' },
  { label: '提示信息', key: 'prompt', color: '#108ee9' },
  { label: '忽略记录', key: 'ignore', color: 'default' },
  { label: '修改记录', key: 'accept', color: 'default' },
];

/**
 * 错误类型
 */
const errorTypes = {
  serious: "严重",
  prompt: "提示",
  normal: "常见",
  suspect: "疑似",
}

/**
 * 错误列表样式
 */
const roleStyle = {
  serious: {
    borderLeft: '2px solid #f50',
    color: '#f50',
  },
  suspect: {
    borderLeft: '2px solid #e3b82f',
    color: '#e3b82f',
  },
  normal: {
    borderLeft: '2px solid #87d068',
    color: '#87d068',
  },
  prompt: {
    borderLeft: '2px solid #108ee9',
    color: '#108ee9',
  },

}

/**
 * 纠错页面
 */
const Proofread: React.FC<StoreProps> = ({ documentStore, proofreadStore }) => {
  const [selectedType, setSelectedType] = useState('all');
  const [selectedErrorTab, setSelectedErrorTab] = useState('all');
  const [started, setStarted] = useState(false);

  /**
   * 顶部筛选区
   * @returns 
   */
  const renderFilterBar = () => (
    <div className={styles[`${prefix}-filter-bar`]}>
      <Space>
        {proofTypes.map(t => (
          <Button
            key={t.value}
            type={selectedType === t.value ? 'primary' : 'default'}
            onClick={() => setSelectedType(t.value)}
          >
            {t.label}
          </Button>
        ))}
      </Space>
      {/*<Space style={{ marginLeft: 16 }}>
        {docTypes.map(t => (
          <Button
            key={t.value}
            type={selectedDocType === t.value ? 'primary' : 'default'}
            onClick={() => setSelectedDocType(t.value)}
          >
            {t.label}
          </Button>
        ))}
      </Space>*/}
    </div>
  );

  /**
   * 全部接受
   */
  const handleAllAccept = () => {
    documentStore.acceptAllError(proofreadStore.errorDatas?.filter(e => !e.isIgnore && !e.isAccept));
    proofreadStore.acceptAllError();
  }

  /**
   * 已选择区域
   * @returns 
   */
  const renderSelectedBar = () => (
    <div className={styles[`${prefix}-selected-bar`]}>
      {/*<div className={styles[`${prefix}-selected-bar-label`]}>
        {errorStats.filter(stat => stat.key === selectedErrorTab).map(stat => {
          return (
            <>
              <span>已经选择</span>
              <span style={{ color: stat.color !== 'default' ? stat.color : undefined }}>{stat.label}</span>
              <span>类型</span>
            </>
          )
        })}
      </div>*/}

      <div className={styles[`${prefix}-accept-btn`]}>
        <Button type="default" size="small" onClick={handleAllAccept} disabled={(proofreadStore.errorCountData.accept + proofreadStore.errorCountData.ignore) === proofreadStore.errorCountData.all}>全部接受</Button>
      </div>
      <div className={styles[`${prefix}-review-btn`]}>
        <Button type="primary" size="small" onClick={documentProofread}>重新校验</Button>
      </div>
    </div>
  )

  /**
   * 错误统计区
   * @returns 
   */
  const renderErrorStats = () => (
    <div className={styles[`${prefix}-stats-bar`]}>
      <div className={styles[`${prefix}-stats-label`]}>文本校对</div>
      <div className={styles[`${prefix}-stats-grid`]}>
        {errorStats.map(stat => (
          <div
            key={stat.key}
            className={classNames(
              styles[`${prefix}-stats-grid-item`],
              { [styles[`${prefix}-stats-grid-item-active`]]: selectedErrorTab === stat.key }
            )}
            onClick={() => setSelectedErrorTab(stat.key)}
          >
            <div
              className={styles[`${prefix}-stats-grid-item-value`]}
              style={{ marginRight: 4, color: stat.color !== 'default' ? stat.color : undefined }}
            >
              {proofreadStore.errorCountData[stat.key] || 0}
            </div>
            <div
              className={styles[`${prefix}-stats-grid-item-label`]}
              style={{ marginRight: 4, color: stat.color !== 'default' ? stat.color : undefined }}
            >
              {stat.label}
            </div>
          </div>
        ))}
      </div>
    </div>
  );

  /**
   * 错误列表点击事件
   * @param item 
   */
  const handleErrorItemClick = (item: ErrorData) => {
    !item.isAccept && !item.isIgnore && documentStore.selectError(item.originalText);
  }

  /**
   * 错误列表接受事件
   * @param item 
   */
  const handleErrorItemAccept = (item: ErrorData) => {
    documentStore.replaceText(item.originalText, item.result);
    proofreadStore.acceptError(item);
  }

  /**
   * 错误列表忽略事件
   * @param item 
   */
  const handleErrorItemIgnore = (item: ErrorData) => {
    proofreadStore.ignoreError(item);
  }

  const getErrorList = () => {
    let list: ErrorData[] = [];
    switch (selectedErrorTab) {
      case 'all':
        list = proofreadStore.errorDatas || [];
        break;
      case 'accept':
        list = proofreadStore.errorDatas.filter((e: ErrorData) => e.isAccept);
        break;
      case 'ignore':
        list = proofreadStore.errorDatas.filter((e: ErrorData) => e.isIgnore);
        break;
      default:
        list = proofreadStore.errorDatas.filter((e: ErrorData) => e.errorLevel === selectedErrorTab && !e.isIgnore && !e.isAccept);
        break;
    }
    return list;
  }

  /**
   * 错误列表
   * @returns
   */
  const renderErrorList = () => (
    <List
      className={styles[`${prefix}-list-area`]}
      dataSource={getErrorList()}
      locale={{ emptyText: '暂无数据' }}
      renderItem={(item: ErrorData) => (
        <List.Item className={styles[`${prefix}-list-item`]} style={roleStyle[item.errorLevel]}>
          <div className={styles[`${prefix}-list-content`]} onClick={() => handleErrorItemClick(item)}>
            <div className={styles[`${prefix}-list-labels`]}>
              {item.tag && <Tag color="red">{item.tag}</Tag>}
              {item.errorLevel && <Tag color={roleStyle[item.errorLevel]?.color}>{errorTypes[item.errorLevel]}</Tag>}
            </div>
            <div className={styles[`${prefix}-list-origin`]}>{item.originalText}</div>
            {item.suggestedFix && (
              <div className={styles[`${prefix}-list-suggestion`]}>{item.suggestedFix}</div>
            )}
          </div>
          <div className={styles[`${prefix}-list-actions`]}>
            {
              (!item.isAccept && !item.isIgnore) && (
                <>
                  <Button key='1' size="small" type='default' onClick={() => handleErrorItemIgnore(item)}>误报</Button>
                  <Button key='2' size="small" type='primary' onClick={() => handleErrorItemAccept(item)}>接受</Button>
                </>
              )}
          </div>
        </List.Item>
      )}
    />
  );

  /**
   * 文档校对
   * @returns 
   */
  const documentProofread = async () => {
    const content = Util.removeHtmlTagsExceptBr(documentStore.content);
    if (!content || content.trim() === '') {
      message.warning('请先输入正文内容');
      return;
    }
    setStarted(true);
    await proofreadStore.documentProofread(documentStore.content);
  }

  /**
   * 引导页内容
   * @returns 
   */
  const renderGuide = () => (
    <div style={{
      display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '70vh', background: '#f8fafc', borderRadius: 12
    }}>
      <img src={bannerImg} alt="引导插图" style={{ width: 50, marginBottom: 32 }} />
      <div style={{ fontSize: 16, color: '#222', marginBottom: 24 }}>检查文件正文中存在的问题或错误</div>
      <Button type="primary" size="large" onClick={documentProofread}>开始校对</Button>
    </div>
  );

  return (
    <div className={styles[`${prefix}-container`]}>
      {!started ? (
        <div style={{ width: '100%', display: 'flex', justifyContent: 'center', alignItems: 'center', background: 'rgb(248, 250, 252)' }}>
          {renderGuide()}
        </div>
      ) : (
        <>
          {proofreadStore.loading ? (
            <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100%', width: '100%' }}>
              <Spin size="large" tip="正在校对..." />
            </div>
          ) : (
            <>
              <div className={styles[`${prefix}-container-left`]}>
                {/* 顶部筛选区 */}
                {/*renderFilterBar()*/}
                {/* 错误统计区 */}

                {/* 全部接受按钮 */}
                {renderSelectedBar()}

                {/* 错误列表 */}
                {renderErrorList()}

              </div>
              <div className={styles[`${prefix}-container-right`]}>
                {renderErrorStats()}
              </div>
            </>
          )}
        </>

      )}
    </div>
  );
};

export default inject('documentStore', 'proofreadStore')(observer(Proofread)); 